import axios from 'axios';
import {getLocal} from '.'
class Http {
  // 基础路径
  // baseURL = 'http://119.23.253.82:4000';
  baseURL = 'http://localhost:4000';
  // 超时时间
  timeout = 5000;
  constructor() {}
  mergeOptions(options) {
    return {
      baseURL: this.baseURL,
      timeout: this.timeout,
      ...options,
    };
  }
  createInterceptor(instance) {
    instance.interceptors.request.use(
      (options) => {

        const info = getLocal('info')
        // 加上token
        if (info && info.token) {
          options.headers.Authorization = 'Bearer ' + info.token
        }
        return options;
      },
      (err) => {
        return Promise.reject(err);
      },
    );

    instance.interceptors.response.use((res) => res.data)
  }
  request(options) {
    // 创建单独的axios实例，好处是单独为每个请求创建拦截器
    const instance = axios.create();
    // 设置拦截器
    this.createInterceptor(instance);
    // 合并请求对象
    options = this.mergeOptions(options);
    return instance(options);
  }
  // get请求
  get(url, options = {}) {
    return this.request({
      url,
      method: 'get',
      ...options,
    });
  }

  // post请求
  post(url, options = {}) {
    return this.request({
      url,
      method: 'post',
      ...options,
    });
  }

  // put请求
  put(url, options = {}) {
    return this.request({
      url,
      method: 'put',
      ...options,
    });
  }

  // delete请求
  delete(url, options = {}) {
    return this.request({
      url,
      method: 'delete',
      ...options,
    });
  }
}
const http = new Http();

export default http;
